import { xmlToJson } from '@/utils/xml'
import { saveTempFile } from '@/utils/file'
/**
 * @Author: lcq
 * @Date: 2024-12-26 23:00:58
 * @brief: 获取头像base64格式
 * @param {*} user
 * @return {*}
 */
export async function getAvatarBase64(user) {
  const file = await user?.avatar?.()
  return 'data:image/png;base64,' + file.buffer.toString('base64')
}

/**
 * @Author: lcq
 * @Date: 2024-12-27 09:46:25
 * @brief: 获取用户信息
 * @param {*} contact
 * @return {*}
 */
export async function getUserInfo(contact) {
  const avatar = await getAvatarBase64(contact)
  return {
    ...contact?.payload,
    avatar
  }
}
/**
 * @Author: lcq
 * @Date: 2024-12-27 19:54:09
 * @brief: 获取消息详情
 * @param {*} bot
 * @param {*} msg
 * @return {*}
 */
export async function getMessageDetail(bot, msg) {
  const contactSelf = bot.currentUser
  const botName = '@' + contactSelf.name() // 机器人名称
  const contact = msg.talker() // 发消息人
  const userInfo = await getUserInfo(contact)

  const room = msg.room() // 是否是群消息
  const roomName = (await room?.topic()) || null // 群名称
  // const alias = (await contact.alias()) || (await contact.name()) // 发消息人昵称
  // const isText = msg.type() === bot.Message.Type.Text // 消息类型是否为文本

  const isRoom = !!room // 是否群聊
  const isOfficial = contact.type() === bot.Contact.Type.Official
  const isSelf = botName === `@${userInfo.alias}` || botName === `@${userInfo.name}` // 是否是机器人自己
  const message = msg.payload
  message.msgType = bot.Message.Type[message.type]
  message.detail = await convertMessageToDetail(bot, msg)
  return {
    userInfo,
    message, // 消息内容
    isRoom,
    roomName,
    isOfficial,
    isSelf
  }
}
/**
 * @Author: lcq
 * @Date: 2024-12-27 19:54:20
 * @brief: 获取自己消息详情
 * @param {*} bot
 * @param {*} room
 * @param {*} text
 * @return {*}
 */
export async function createSelfMessageDetail(bot, room, text = '', type = '7') {
  const contactSelf = bot.currentUser
  const userInfo = await getUserInfo(contactSelf)
  const message = {
    text,
    timestamp: new Date().getTime() / 1000
  }
  message.msgType = bot.Message.Type[type]
  message.detail = null
  return {
    userInfo,
    message, // 消息内容
    isRoom: !!room,
    isOfficial: false,
    roomName: (await room?.topic()) || null,
    isSelf: true
  }
}

/**
 * @Author: lcq
 * @Date: 2024-12-29 16:18:35
 * @brief: 消息转换
 * @param {*} msg
 * @return {*}
 */
export async function convertMessageToDetail(bot, msg) {
  switch (msg.type()) {
    case bot.Message.Type.Transfer:
      return msg.text().match(/<des><!\[CDATA\[([^\]]+)\]/im)?.[1]
    case bot.Message.Type.Contact:
      try {
        const {
          msg: { $ }
        } = await xmlToJson(msg.text())
        return $
      } catch (_) {
        console.log('xmlToJson error', _)
      }
      break
    case bot.Message.Type.Recalled:
      try {
        const {
          sysmsg: { revokemsg }
        } = await xmlToJson(msg.text())
        msg.payload.text = revokemsg.replacemsg
        return revokemsg
      } catch (_) {
        console.log('xmlToJson error', _)
      }
      break
  }
  const conversionMethods = [
    'toUrlLink', // 链接
    'toMiniProgram', // 小程序
    'toContact', // 联系人
    // 'toLocation', // 位置
    'toPost', // 帖子
    'toFileBox' // 文件
    // 'toSayable'
  ]
  for (const method of conversionMethods) {
    try {
      const result = await msg[method]()
      if (result) {
        const filePath = result.buffer && (await saveTempFile(result.name, result.buffer))
        if (filePath) {
          result.filePath = filePath
          delete result?.buffer
          delete result?.base64
        }
        return result
      }
    } catch (_e) {
      // Log the error or handle it as needed
      // console.error(e)
    }
  }
  return null
}
